package com.loyal.mwm.ui

import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.AsyncTask
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.loyal.mwm.R
import com.loyal.mwm.base.BaseSwipeActivity
import com.loyal.mwm.databinding.ActivityShareBinding
import com.loyal.mwm.libs.manager.AppAdapter
import com.loyal.mwm.libs.manager.AppBean
import com.loyal.mwm.util.ImageUtil
import com.loyal.mwm.util.PreferUtil
import java.util.*

class ShareActivity : BaseSwipeActivity<ActivityShareBinding>(),
    SwipeRefreshLayout.OnRefreshListener {

    private var mQueryAuth: QueryAppAsync? = null
    private val appList: MutableList<AppBean> = ArrayList()
    private var appAdapter: AppAdapter? = null

    override fun actLayoutRes(): Int {
        return R.layout.activity_share
    }

    override fun afterOnCreate() {
        binding.drawable = ImageUtil.getBackground(this)
        initViews()
        appAdapter = AppAdapter(this, appList)
        binding.recyclerView.adapter = appAdapter
        queryList()
    }

    private fun queryList() {
        if (mQueryAuth != null) return
        mQueryAuth = QueryAppAsync()
        mQueryAuth!!.execute()
    }

    private fun initViews() {
        val toolbar = binding.toolbar.root
        toolbar.title = "分享"
        setSupportActionBar(toolbar)
        binding.pullToRefresh.isEnabled = false
        binding.recyclerView.setHasFixedSize(true)
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        binding.pullToRefresh.setOnRefreshListener(this)
    }

    override fun setEdgePosition(): Int {
        return LEFT
    }

    override fun onRefresh() {
        appAdapter!!.clear()
        queryList()
        binding.pullToRefresh.postDelayed({ binding.pullToRefresh.isRefreshing = false }, 2000)
    }

    private inner class QueryAppAsync : AsyncTask<Void?, Int?, Void?>() {
        private var totalApps = 0
        private var actualApps: Int

        init {
            showProgressDialog()
            actualApps = 0
        }

        override fun doInBackground(vararg params: Void?): Void? {
            val packageManager = packageManager
            val packages = packageManager.getInstalledPackages(PackageManager.GET_META_DATA)
            val hiddenApps = PreferUtil.getHiddenApps(this@ShareActivity)
            totalApps = packages.size + hiddenApps.size
            packages.sortWith { p1: PackageInfo, p2: PackageInfo ->
                packageManager.getApplicationLabel(p1.applicationInfo).toString().lowercase(
                    Locale.getDefault()
                ).compareTo(
                    packageManager.getApplicationLabel(p2.applicationInfo).toString().lowercase(
                        Locale.getDefault()
                    )
                )
            }
            for (packageInfo in packages) {
                if (!(packageManager.getApplicationLabel(packageInfo.applicationInfo) == "" || packageInfo.packageName == "")) {
                    if (packageInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
                        try {
                            val tempApp = AppBean(
                                packageManager.getApplicationLabel(packageInfo.applicationInfo)
                                    .toString(),
                                packageInfo.packageName,
                                packageInfo.versionName,
                                packageInfo.applicationInfo.sourceDir,
                                packageInfo.applicationInfo.dataDir,
                                packageManager.getApplicationIcon(packageInfo.applicationInfo),
                                false
                            )
                            appList.add(tempApp)
                        } catch (e: OutOfMemoryError) {
                            val tempApp = AppBean(
                                packageManager.getApplicationLabel(packageInfo.applicationInfo)
                                    .toString(),
                                packageInfo.packageName,
                                packageInfo.versionName,
                                packageInfo.applicationInfo.sourceDir,
                                packageInfo.applicationInfo.dataDir,
                                ContextCompat.getDrawable(this@ShareActivity, R.mipmap.icon),
                                false
                            )
                            appList.add(tempApp)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
                actualApps++
                publishProgress(actualApps * 100 / totalApps)
            }
            return null
        }

        override fun onProgressUpdate(vararg values: Int?) {
            super.onProgressUpdate(*values)
            progressDialog.progress = values[0]!!
        }

        override fun onPostExecute(aVoid: Void?) {
            super.onPostExecute(aVoid)
            dismissDialog()
            mQueryAuth = null
            appAdapter!!.refreshData(appList)
            binding.pullToRefresh.isEnabled = true
        }

        override fun onCancelled() {
            super.onCancelled()
            mQueryAuth = null
        }
    }
}